import os
import csv
import sys
import datetime
from odps import ODPS
"""
导出手艺人历史位置日志
(当日完成履约的订单)
"""


def get_yesterday(day_num=1, day_format="%Y-%m-%d"):
    today = datetime.date.today()
    oneday = datetime.timedelta(days=day_num)
    yesterday = today - oneday
    return yesterday.strftime(day_format)


if __name__ == '__main__':
    try:
        day_interval = int(sys.argv[1])
    except:
        day_interval = 1
    if day_interval < 1:
        day_interval = 1
    select_day = get_yesterday(day_interval, '%Y%m%d')
    save_day = get_yesterday(day_interval)
    target_dir = "/data/disp/" + save_day + "/"
    try:
        os.makedirs(target_dir)
    except:
        pass
    target_file = target_dir + "artisan_logs.csv"
    if not os.path.exists(target_file):
        # 这里替换成你自己的存储连接
        odps = ODPS('xxx', 'xxxxxxxxxxx', 'XXX_APP', endpoint='http://service.odps.aliyun.com/api')

        inventory_sql = """
            SELECT user_id as artisan_id, action_time, longitude, latitude FROM xxx_ods.ods_log_art_user_flow where ds='%s'
            """ % select_day

        with odps.execute_sql(inventory_sql).open_reader() as reader:
            result_df = reader.to_pandas()

        if result_df is not None:
            result_df.to_csv(target_file, quoting=csv.QUOTE_ALL)
            print('export artisan logs:' + str(len(result_df)))
